import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
//重复路由跳转报错BUG修复
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [

] //初始化路由表数组


//自动映射路由到组件
const autoMap = () => {
  const requireRouterPage = require.context('../views/', true, /\.vue$/)
  //console.log(requireRouterPage.keys())
  requireRouterPage.keys().forEach(fileName => {
    // console.log(fileName)
    const componentConfig = requireRouterPage(fileName)
    //console.log(componentConfig)
    const RouterPageName = fileName.replace(/\.\/(.*?)\.vue/, "$1")
    console.log(RouterPageName)
    const RouterPagePathInfo = RouterPageName.split('/')
    console.warn(`自动路由：[${RouterPageName}]`)
    // const RouterPagePath=RouterPageName.replace(/\-/g,'')
    // RouterPagePathInfo.filter((e)=>{return e==RouterPageName})
    if (RouterPagePathInfo.length == 1) {
      routes.push({
        path: '/' + (RouterPageName == 'Home' ? '' : RouterPageName),
        name: RouterPageName,
        component: ()=>import('../views/'+RouterPageName+'.vue')//componentConfig.default
      })
    }
    else {
      // console.log(routes.find((ele)=>{return ele.name==RouterPagePathInfo[0]}))
      routes.map((ele) => {
        if (ele.name == RouterPagePathInfo[0]) {
          if(!ele.hasOwnProperty('children'))
          {
            ele.children=[]
          }
          ele.children.push({
            path: RouterPagePathInfo[1]=='index'?'/':RouterPagePathInfo[1],
            name: RouterPagePathInfo.join('-'),
            component: ()=>import('../views/'+RouterPageName+'.vue')//componentConfig.default
          })
        }
      })
    }

  })
  //console.log(routes)
  return new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes
  })
}
export default { autoMap }
